<template>
  <PageContainer title="清洁管理">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="任务筛选">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入任务编号或设备名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="任务状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择任务状态"
          clearable
        >
          <el-option label="待执行" value="pending" />
          <el-option label="执行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
          <el-option label="异常" value="exception" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务类型">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择任务类型"
          clearable
        >
          <el-option label="定期清洁" value="regular" />
          <el-option label="紧急清洁" value="emergency" />
          <el-option label="维护清洁" value="maintenance" />
          <el-option label="深度清洁" value="deep" />
        </el-select>
      </el-form-item>
      <el-form-item label="执行人员">
        <el-select
          v-model="searchForm.assigneeId"
          placeholder="请选择执行人员"
          clearable
          filterable
        >
          <el-option
            v-for="staff in staffOptions"
            :key="staff.id"
            :label="staff.name"
            :value="staff.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </SearchForm>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="Calendar"
        icon-bg="#409EFF"
        :value="cleanupStats.totalTasks"
        label="总任务数"
        :trend="cleanupStats.totalTrend"
      />
      <StatCard
        :icon="Clock"
        icon-bg="#E6A23C"
        :value="cleanupStats.pendingTasks"
        label="待执行任务"
        :trend="cleanupStats.pendingTrend"
      />
      <StatCard
        :icon="CircleCheck"
        icon-bg="#67C23A"
        :value="cleanupStats.completedTasks"
        label="已完成任务"
        :trend="cleanupStats.completedTrend"
      />
      <StatCard
        :icon="User"
        icon-bg="#909399"
        :value="cleanupStats.activeStaff"
        label="活跃人员"
        :trend="cleanupStats.staffTrend"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleCreateTask"
        >
          <el-icon><Plus /></el-icon>
          创建任务
        </el-button>
        <el-button
          type="success"
          :disabled="!selectedRows.length"
          @click="handleBatchAssign"
        >
          <el-icon><User /></el-icon>
          批量分配
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedRows.length"
          @click="handleBatchCancel"
        >
          <el-icon><Close /></el-icon>
          批量取消
        </el-button>
        <el-button
          type="info"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadCleanupList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 清洁任务表格 -->
    <DataTable
      :data="cleanupList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="任务ID" width="100" />
      <el-table-column prop="taskNo" label="任务编号" width="150" />
      <el-table-column label="设备信息" width="200">
        <template #default="{ row }">
          <div class="device-info">
            <div class="device-name">{{ row.deviceName }}</div>
            <div class="device-location">{{ row.deviceLocation }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" width="100">
        <template #default="{ row }">
          <el-tag
            :type="getPriorityTag(row.priority)"
            size="small"
          >
            {{ getPriorityText(row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="执行人员" width="120">
        <template #default="{ row }">
          <div v-if="row.assigneeName" class="assignee-info">
            <div class="assignee-name">{{ row.assigneeName }}</div>
            <div class="assignee-phone">{{ row.assigneePhone }}</div>
          </div>
          <span v-else class="text-muted">未分配</span>
        </template>
      </el-table-column>
      <el-table-column label="计划时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDateTime(row.scheduledAt) }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="180">
        <template #default="{ row }">
          {{ row.startedAt ? formatDateTime(row.startedAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="完成时间" width="180">
        <template #default="{ row }">
          {{ row.completedAt ? formatDateTime(row.completedAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="耗时" width="100">
        <template #default="{ row }">
          <span v-if="row.duration" class="duration-text">
            {{ formatDuration(row.duration) }}
          </span>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-button
            v-if="row.status === 'pending'"
            type="success"
            size="small"
            @click="handleAssign(row)"
          >
            分配
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  command="start" 
                  :disabled="row.status !== 'pending'"
                >
                  开始执行
                </el-dropdown-item>
                <el-dropdown-item 
                  command="complete" 
                  :disabled="row.status !== 'in_progress'"
                >
                  完成任务
                </el-dropdown-item>
                <el-dropdown-item 
                  command="edit" 
                  :disabled="row.status === 'completed'"
                >
                  编辑任务
                </el-dropdown-item>
                <el-dropdown-item command="view-photos">查看照片</el-dropdown-item>
                <el-dropdown-item command="view-report">查看报告</el-dropdown-item>
                <el-dropdown-item 
                  command="cancel" 
                  :disabled="row.status === 'completed' || row.status === 'cancelled'"
                  divided
                >
                  取消任务
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="任务详情"
      width="80%"
    >
      <div v-if="currentTask" class="task-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="任务ID">
                {{ currentTask.id }}
              </el-descriptions-item>
              <el-descriptions-item label="任务编号">
                {{ currentTask.taskNo }}
              </el-descriptions-item>
              <el-descriptions-item label="任务类型">
                <el-tag :type="getTypeTag(currentTask.type)">
                  {{ getTypeText(currentTask.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="任务状态">
                <el-tag :type="getStatusTag(currentTask.status)">
                  {{ getStatusText(currentTask.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="优先级">
                <el-tag :type="getPriorityTag(currentTask.priority)">
                  {{ getPriorityText(currentTask.priority) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="设备名称">
                {{ currentTask.deviceName }}
              </el-descriptions-item>
              <el-descriptions-item label="设备位置">
                {{ currentTask.deviceLocation }}
              </el-descriptions-item>
              <el-descriptions-item label="任务描述">
                {{ currentTask.description }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="执行信息" :column="1" border>
              <el-descriptions-item label="执行人员">
                {{ currentTask.assigneeName || '未分配' }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">
                {{ currentTask.assigneePhone || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="计划时间">
                {{ formatDateTime(currentTask.scheduledAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="开始时间">
                {{ currentTask.startedAt ? formatDateTime(currentTask.startedAt) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="完成时间">
                {{ currentTask.completedAt ? formatDateTime(currentTask.completedAt) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="执行耗时">
                {{ currentTask.duration ? formatDuration(currentTask.duration) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建人员">
                {{ currentTask.createdBy }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDateTime(currentTask.createdAt) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <!-- 清洁项目 -->
        <div class="cleanup-items" style="margin-top: 20px;">
          <h4>清洁项目</h4>
          <el-table :data="currentTask.cleanupItems" size="small">
            <el-table-column prop="name" label="项目名称" />
            <el-table-column prop="description" label="项目描述" />
            <el-table-column label="完成状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.completed ? 'success' : 'info'">
                  {{ row.completed ? '已完成' : '未完成' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="completedAt" label="完成时间" width="180">
              <template #default="{ row }">
                {{ row.completedAt ? formatDateTime(row.completedAt) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>

        <!-- 执行照片 -->
        <div class="task-photos" style="margin-top: 20px;">
          <h4>执行照片</h4>
          <div class="photo-gallery">
            <div
              v-for="(photo, index) in currentTask.photos"
              :key="index"
              class="photo-item"
            >
              <el-image
                :src="photo.url"
                :alt="photo.description"
                fit="cover"
                :preview-src-list="currentTask.photos.map((p: any) => p.url)"
                :initial-index="index"
                class="task-photo"
              />
              <div class="photo-description">{{ photo.description }}</div>
              <div class="photo-time">{{ formatDateTime(photo.createdAt) }}</div>
            </div>
          </div>
        </div>

        <!-- 执行报告 -->
        <div v-if="currentTask.report" class="task-report" style="margin-top: 20px;">
          <h4>执行报告</h4>
          <el-card>
            <div class="report-content">
              <div class="report-summary">
                <strong>总结：</strong>{{ currentTask.report.summary }}
              </div>
              <div class="report-details">
                <strong>详细说明：</strong>{{ currentTask.report.details }}
              </div>
              <div class="report-issues">
                <strong>发现问题：</strong>{{ currentTask.report.issues || '无' }}
              </div>
              <div class="report-suggestions">
                <strong>改进建议：</strong>{{ currentTask.report.suggestions || '无' }}
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      :title="isEdit ? '编辑任务' : '创建任务'"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskNo">
              <el-input
                v-model="taskForm.taskNo"
                placeholder="系统自动生成"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="type">
              <el-select
                v-model="taskForm.type"
                placeholder="请选择任务类型"
              >
                <el-option label="定期清洁" value="regular" />
                <el-option label="紧急清洁" value="emergency" />
                <el-option label="维护清洁" value="maintenance" />
                <el-option label="深度清洁" value="deep" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目标设备" prop="deviceId">
              <el-select
                v-model="taskForm.deviceId"
                placeholder="请选择设备"
                filterable
              >
                <el-option
                  v-for="device in deviceOptions"
                  :key="device.id"
                  :label="`${device.name} (${device.location})`"
                  :value="device.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select
                v-model="taskForm.priority"
                placeholder="请选择优先级"
              >
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行人员" prop="assigneeId">
              <el-select
                v-model="taskForm.assigneeId"
                placeholder="请选择执行人员"
                clearable
              >
                <el-option
                  v-for="staff in staffOptions"
                  :key="staff.id"
                  :label="staff.name"
                  :value="staff.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="scheduledAt">
              <el-date-picker
                v-model="taskForm.scheduledAt"
                type="datetime"
                placeholder="请选择计划时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="清洁项目">
          <div class="cleanup-items-form">
            <div
              v-for="(item, index) in taskForm.cleanupItems"
              :key="index"
              class="cleanup-item"
            >
              <el-input
                v-model="item.name"
                placeholder="项目名称"
                style="width: 200px; margin-right: 10px;"
              />
              <el-input
                v-model="item.description"
                placeholder="项目描述"
                style="width: 300px; margin-right: 10px;"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeCleanupItem(index)"
              >
                删除
              </el-button>
            </div>
            <el-button
              type="primary"
              size="small"
              @click="addCleanupItem"
            >
              添加项目
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="taskForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTaskSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配任务对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配任务"
      width="500px"
    >
      <el-form
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        label-width="100px"
      >
        <el-form-item label="执行人员" prop="assigneeId">
          <el-select
            v-model="assignForm.assigneeId"
            placeholder="请选择执行人员"
            style="width: 100%"
          >
            <el-option
              v-for="staff in staffOptions"
              :key="staff.id"
              :label="`${staff.name} (${staff.phone})`"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="scheduledAt">
          <el-date-picker
            v-model="assignForm.scheduledAt"
            type="datetime"
            placeholder="请选择计划时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分配备注">
          <el-input
            v-model="assignForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入分配备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignSubmit" :loading="submitting">
          确认分配
        </el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Calendar,
  Clock,
  CircleCheck,
  User,
  Plus,
  Close,
  Download,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useCleanupStore } from '@/stores/cleanup'
import { useDeviceStore } from '@/stores/device'
import { formatDateTime } from '@/utils'

const cleanupStore = useCleanupStore()
const deviceStore = useDeviceStore()

const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const taskDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const isEdit = ref(false)
const currentTask = ref<any>(null)
const selectedRows = ref<any[]>([])
const taskFormRef = ref<FormInstance>()
const assignFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  type: '',
  assigneeId: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 清洁统计
const cleanupStats = reactive({
  totalTasks: '486',
  totalTrend: '+12.5%',
  pendingTasks: '23',
  pendingTrend: '+8.2%',
  completedTasks: '445',
  completedTrend: '+15.8%',
  activeStaff: '12',
  staffTrend: '+2.1%'
})

// 清洁任务列表
const cleanupList = ref<any[]>([])

// 设备选项
const deviceOptions = ref<any[]>([])

// 人员选项
const staffOptions = ref<any[]>([
  { id: 1, name: '张三', phone: '13800138001' },
  { id: 2, name: '李四', phone: '13800138002' },
  { id: 3, name: '王五', phone: '13800138003' },
  { id: 4, name: '赵六', phone: '13800138004' }
])

// 任务表单
const taskForm = reactive({
  taskNo: '',
  type: 'regular',
  deviceId: '',
  priority: 'medium',
  assigneeId: '',
  scheduledAt: '',
  description: '',
  cleanupItems: [
    { name: '外观清洁', description: '清洁设备外观表面' },
    { name: '内部清理', description: '清理设备内部垃圾' }
  ],
  remark: ''
})

// 分配表单
const assignForm = reactive({
  assigneeId: '',
  scheduledAt: '',
  remark: ''
})

// 表单验证规则
const taskRules: FormRules = {
  type: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  deviceId: [
    { required: true, message: '请选择目标设备', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  scheduledAt: [
    { required: true, message: '请选择计划时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
    { min: 10, max: 500, message: '任务描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

const assignRules: FormRules = {
  assigneeId: [
    { required: true, message: '请选择执行人员', trigger: 'change' }
  ],
  scheduledAt: [
    { required: true, message: '请选择计划时间', trigger: 'change' }
  ]
}

// 获取任务类型标签
const getTypeTag = (type: string) => {
  switch (type) {
    case 'regular':
      return 'primary'
    case 'emergency':
      return 'danger'
    case 'maintenance':
      return 'warning'
    case 'deep':
      return 'success'
    default:
      return 'info'
  }
}

// 获取任务类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'regular':
      return '定期清洁'
    case 'emergency':
      return '紧急清洁'
    case 'maintenance':
      return '维护清洁'
    case 'deep':
      return '深度清洁'
    default:
      return '未知类型'
  }
}

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case 'pending':
      return 'info'
    case 'in_progress':
      return 'warning'
    case 'completed':
      return 'success'
    case 'cancelled':
      return 'info'
    case 'exception':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待执行'
    case 'in_progress':
      return '执行中'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    case 'exception':
      return '异常'
    default:
      return '未知状态'
  }
}

// 获取优先级标签
const getPriorityTag = (priority: string) => {
  switch (priority) {
    case 'low':
      return 'info'
    case 'medium':
      return 'primary'
    case 'high':
      return 'warning'
    case 'urgent':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'low':
      return '低'
    case 'medium':
      return '中'
    case 'high':
      return '高'
    case 'urgent':
      return '紧急'
    default:
      return '未知'
  }
}

// 格式化持续时间
const formatDuration = (minutes: number) => {
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return `${hours}小时${mins}分钟`
}

// 加载清洁任务列表
const loadCleanupList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await cleanupStore.fetchCleanupList(params)
    cleanupList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载清洁任务列表失败')
  } finally {
    loading.value = false
  }
}

// 加载设备选项
const loadDeviceOptions = async () => {
  try {
    const response = await deviceStore.fetchDeviceList({ page: 1, size: 1000 })
    deviceOptions.value = response.list
  } catch (error) {
    console.error('加载设备选项失败:', error)
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadCleanupList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadCleanupList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadCleanupList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadCleanupList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 创建任务
const handleCreateTask = () => {
  isEdit.value = false
  Object.assign(taskForm, {
    taskNo: '',
    type: 'regular',
    deviceId: '',
    priority: 'medium',
    assigneeId: '',
    scheduledAt: '',
    description: '',
    cleanupItems: [
      { name: '外观清洁', description: '清洁设备外观表面' },
      { name: '内部清理', description: '清理设备内部垃圾' }
    ],
    remark: ''
  })
  taskDialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row: any) => {
  // 模拟获取任务详细信息
  currentTask.value = {
    ...row,
    createdBy: '管理员',
    cleanupItems: [
      {
        name: '外观清洁',
        description: '清洁设备外观表面',
        completed: true,
        completedAt: '2024-01-15 14:30:00',
        remark: '清洁完成'
      },
      {
        name: '内部清理',
        description: '清理设备内部垃圾',
        completed: true,
        completedAt: '2024-01-15 14:45:00',
        remark: '垃圾已清理'
      }
    ],
    photos: [
      {
        url: 'https://via.placeholder.com/300x200?text=清洁前',
        description: '清洁前照片',
        createdAt: '2024-01-15 14:00:00'
      },
      {
        url: 'https://via.placeholder.com/300x200?text=清洁后',
        description: '清洁后照片',
        createdAt: '2024-01-15 15:00:00'
      }
    ],
    report: {
      summary: '设备清洁任务已完成，设备运行正常',
      details: '对设备进行了全面清洁，包括外观清洁和内部垃圾清理。设备各项功能正常，无异常情况。',
      issues: '发现设备门锁有轻微松动',
      suggestions: '建议定期检查门锁紧固情况'
    }
  }
  detailDialogVisible.value = true
}

// 分配任务
const handleAssign = (row: any) => {
  currentTask.value = row
  Object.assign(assignForm, {
    assigneeId: '',
    scheduledAt: row.scheduledAt,
    remark: ''
  })
  assignDialogVisible.value = true
}

// 任务表单提交
const handleTaskSubmit = async () => {
  if (!taskFormRef.value) return
  
  try {
    await taskFormRef.value.validate()
    submitting.value = true
    
    // 调用创建/更新任务API
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    taskDialogVisible.value = false
    loadCleanupList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

// 分配表单提交
const handleAssignSubmit = async () => {
  if (!assignFormRef.value) return
  
  try {
    await assignFormRef.value.validate()
    submitting.value = true
    
    // 调用分配任务API
    ElMessage.success('分配成功')
    assignDialogVisible.value = false
    loadCleanupList()
  } catch (error) {
    ElMessage.error('分配失败')
  } finally {
    submitting.value = false
  }
}

// 添加清洁项目
const addCleanupItem = () => {
  taskForm.cleanupItems.push({
    name: '',
    description: ''
  })
}

// 删除清洁项目
const removeCleanupItem = (index: number) => {
  taskForm.cleanupItems.splice(index, 1)
}

// 批量分配
const handleBatchAssign = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量分配选中的 ${selectedRows.value.length} 个任务吗？`,
      '批量分配',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量分配API
    ElMessage.success('批量分配成功')
    loadCleanupList()
  } catch (error) {
    // 用户取消
  }
}

// 批量取消
const handleBatchCancel = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量取消选中的 ${selectedRows.value.length} 个任务吗？`,
      '批量取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量取消API
    ElMessage.success('批量取消成功')
    loadCleanupList()
  } catch (error) {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'start':
      ElMessage.info('开始执行功能开发中...')
      break
    case 'complete':
      ElMessage.info('完成任务功能开发中...')
      break
    case 'edit':
      ElMessage.info('编辑任务功能开发中...')
      break
    case 'view-photos':
      ElMessage.info('查看照片功能开发中...')
      break
    case 'view-report':
      ElMessage.info('查看报告功能开发中...')
      break
    case 'cancel':
      ElMessage.info('取消任务功能开发中...')
      break
  }
}

onMounted(() => {
  loadCleanupList()
  loadDeviceOptions()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.device-info {
  .device-name {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .device-location {
    font-size: 12px;
    color: #909399;
  }
}

.assignee-info {
  .assignee-name {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .assignee-phone {
    font-size: 12px;
    color: #909399;
  }
}

.text-muted {
  color: #909399;
}

.duration-text {
  font-weight: 600;
  color: #409EFF;
}

.task-detail {
  .cleanup-items,
  .task-photos,
  .task-report {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }

  .photo-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;

    .photo-item {
      text-align: center;

      .task-photo {
        width: 100%;
        height: 150px;
        border-radius: 4px;
      }

      .photo-description {
        margin-top: 8px;
        font-size: 12px;
        color: #303133;
        font-weight: 600;
      }

      .photo-time {
        font-size: 11px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }

  .report-content {
    line-height: 1.6;

    > div {
      margin-bottom: 12px;

      strong {
        color: #303133;
        margin-right: 8px;
      }
    }
  }
}

.cleanup-items-form {
  .cleanup-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .task-detail {
    .photo-gallery {
      grid-template-columns: 1fr;
    }
  }

  .cleanup-items-form {
    .cleanup-item {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;
    }
  }
}
</style>